<template>
  <div class="flyUser">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 10000, str: '1w', unit:'+'}"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page flyUser-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :default-select-key="defaultSelectKey" :filter-list="filterList" is-show-config show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <MoreOpeator
          v-if="hasRouteAuth('crm:flyUser:updateAccount') || hasRouteAuth('crm:flyUser:updateSupplier')"
          :list="moreOpeatorOptions"
          style="margin:0 10px;"
        />
        <template v-if="hasRouteAuth('crm:flyUser:batchSetStatus') && !isDisableTab">
          <el-button type="primary" size="small" class="submit-btn" @click.native="batchSetStatus(1)">
            <div class="enable-btn">
              一键启用
              <el-tooltip placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">启用选中的飞来用户，并自动创建和关联「同名供应商」、以及相关账号。若需要关联「非同名的供应商」，请先单独操作该用户关联唯一供应商，该用户下的账号将自动关联该唯一供应商。</div>
                <el-image :src="tipIcon" class="tipIcon"/>
              </el-tooltip>
              <i v-if="batchLoading" class="el-icon-loading"/>
          </div></el-button>
        </template>
        <el-button v-if="hasRouteAuth('crm:flyUser:batchSetStatus') && isDisableTab" type="danger" style="height: 32px" size="small" plain @click="batchSetStatus(2)">禁用<i v-if="batchLoading" class="el-icon-loading"/></el-button>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :border="true"
            :row-height="rowHeight(55)"
            :height="setTableHeight"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"
            />
            <u-table-column align="left" label="用户ID" min-width="150">
              <template slot-scope="scope">
                <div v-if="scope.row.wxUserCode" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                  <ToolTip :content="scope.row.wxUserCode" is-can-click @handelClick="toDetail(scope.row)" />
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="姓名" min-width="130">
              <template slot-scope="scope">
                <div class="flex-center">
                  <ToolTip :content="scope.row.userName" :style="{maxWidth: scope.row.waitUpdate ? 'calc(100% - 32px)' : '100%'}"/>
                  <div v-if="scope.row.waitUpdate" class="new-tag">New</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="微信昵称" min-width="90">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.nickName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accountName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="下单平台" min-width="120">
              <template slot-scope="scope">
                <div class="flex-center">
                  <ToolTip :content="scope.row.platformTypeName" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="粉丝数" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="handleFans(scope.row.fansNum)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="标签" min-width="210">
              <template slot-scope="scope">
                <TagSelect v-model="scope.row.tagName" mode="list" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="接单偏好">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.preference" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="地域" min-width="180">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.region" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="供应商" min-width="160">
              <template slot-scope="scope">
                <el-tooltip
                  v-if="Array.isArray(scope.row.affiliatedSuppliers) && scope.row.affiliatedSuppliers.length"
                  :open-delay="800"
                  placement="top">
                  <div slot="content">
                    <template v-for="supplier in scope.row.affiliatedSuppliers">
                      <div :key="supplier.supplierId">
                        <span class="supplier-tooltip-name" style="cursor: pointer" @click="toSupplierDetail(supplier.supplierId)">{{ supplier.supplierName }}</span>
                      </div>
                    </template>
                  </div>
                  <div class="ellipsisOne">{{ getAffiliatedSuppliers(scope.row.affiliatedSuppliers) }}</div>
                </el-tooltip>
                <div v-else style="color:#999999">未关联</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <div style="display:flex;align-items:center;">
                  <span :style="{backgroundColor: getFlyStatusColor(scope.row.status)}" class="dot"/>
                  {{ scope.row.status | flyUserStatus }}
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="微信号" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.wxCode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="手机" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.phone" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="邀请人">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invitee" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="入驻类型" sortable="custom" prop="settledInType" min-width="130">
              <template slot-scope="scope">
                <ToolTip :content="settledInTypeMap(scope.row.settledInType)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新人">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.updator" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" sortable="custom" prop="createTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新时间" min-width="160" sortable="custom" prop="updateTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.updateTime,'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="最近登录时间" min-width="160" sortable="custom" prop="lastLoginTime">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.lastLoginTime,'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="operate">
                  <div v-if="!showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: showMobilePage},
                      {label: '启用', handelClick: () => {setUserStatus(scope.row.id,1,scope.row.affiliatedSuppliers)}, auth: hasRouteAuth('crm:flyUser:setStatus') && scope.row.status !== 1},
                      {label: '禁用', handelClick: () => {setUserStatus(scope.row.id,2)}, auth: hasRouteAuth('crm:flyUser:setStatus') && scope.row.status !== 2},
                      {label: '发起签约', handelClick: () => {signUpCreate(scope.row.id)}, auth: hasRouteAuth('crm:flyUser:createSignUp')},
                      {label: '新建供应商', handelClick: () => toCreateSupplier(), auth: hasRouteAuth('crm:flyUser:createSupplier')},
                      {label: '关联供应商', handelClick: () => {openDialog(scope.row.id, scope.row.affiliatedSuppliers, scope.row.userName)}, auth: hasRouteAuth('crm:flyUser:relateSupplier')},
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" is-show-config show-mobile-icon show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              v-if="hasRouteAuth('crm:flyUser:updateAccount') || hasRouteAuth('crm:flyUser:updateSupplier')"
              ref="moreOpeatorRef"
              :list="[
                {label: '一键启用', handelClick: () => {batchSetStatus(1)}, auth: hasRouteAuth('crm:flyUser:batchSetStatus') && !isDisableTab,tip: '启用选中的飞来用户，并自动创建和关联「同名供应商」、以及相关账号。若需要关联「非同名的供应商」，请先单独操作该用户关联唯一供应商，该用户下的账号将自动关联该唯一供应商。。'},
                {label: '禁用', handelClick: () => {batchSetStatus(2)}, auth: hasRouteAuth('crm:flyUser:batchSetStatus') && isDisableTab},
                ...moreOpeatorOptions
              ]"
              show-mobile-icon
            />
          </template>
          <template v-else>
            <div style="flex:1;display:flex;align-items:center;">
              <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
            </div>
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <supplierDialog ref="supplierDialog" @succese="fetchData()"/>
    <updateCheckDialog ref="updateCheckDialogRef" @close="handleUpdateCheckClose"/>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { TAG_MODULES } from '@/utils/const';
// 组件
import supplierDialog from './components/supplierDialog';
import updateCheckDialog from './components/updateCheckDialog';
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import TagSelect from '@/components/Common/tagSelect';
// fitter
import { numberTextFormat } from '@/filters/number';
import { flyUserStatus, getFlyStatusColor } from '@/filters/status';
// api
import { tabList, flyUserList, batchUpdate, getUpdateStatus, batchSetStatus } from '@/api/flyUser';
import { getTagAll } from '@/api/config';
import { platformList } from '@/api/select';
import { format } from '@/filters/date';
import TableAdaptive from '@/mixins/tableAdaptive';
import { allRegionData } from '@/utils/areaConfig';
import { showModal } from '@/utils/message';
// icon
import tipIcon from '@/assets/supplier/tipIcon.png';
// mixins
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
import mixins from './mixins';

export default {
  filters: {
    flyUserStatus
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    supplierDialog,
    updateCheckDialog,
    MoreOpeator,
    TagSelect
  },
  mixins: [TableAdaptive, mixins, tableSelections, mobileTable],
  data() {
    return {
      tipIcon,
      TAG_MODULES,
      tabs: [],
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      tabStatus: -1,
      page: 1,
      perPage: 20,
      sortName: '',
      sortType: '',
      paramsObj: {},
      listLoading: false,
      cancelToken: null,
      orderPlatformOption: [], // 下单平台
      tagTreeList: [],
      status: [
        { value: 3, label: '待提交' },
        { value: 0, label: '待审批' },
        { value: 1, label: '启用' },
        { value: 2, label: '禁用' }
      ],
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'updateTime',
        start: 'updateStartTime',
        end: 'updateEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'lastLoginTime',
        start: 'lastLoginStartTime',
        end: 'lastLoginEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'fansNum',
        start: 'fansNumStart',
        end: 'fansNumEnd',
        type: 'fansNums'
      }],
      idKey: 'id', // 多选框参数
      tableRefName: 'tableRef',
      isUmyTable: true,
      isAccountUpdating: false,
      isUserUpdating: false,
      timer: null, // 定时器
      defaultSelectKey: '',
      batchLoading: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isDisableTab() {
      return this.tabStatus === 1;
    },
    linkAccountStatus() {
      return [{
        label: '待关联', value: 0
      }, {
        label: '部分关联', value: 1
      }, {
        label: '已关联', value: 2
      }];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'userName', name: '姓名', labelWidth: '100px', type: 'input' },
        { keyword: 'wxUserCode', name: '用户ID', labelWidth: '100px', type: 'input' },
        { keyword: 'accountName', name: '账号', labelWidth: '100px', type: 'input', placeholder: '搜索多个用英文分号“;”隔开' },
        { keyword: 'fansNum', name: '粉丝数', labelWidth: '100px', onlyInteger: true, type: 'inputRange', isRequired: true, startPlaceholder: '最低粉丝数', endPlaceholder: '最高粉丝数', max: 999999999 },
        { keyword: 'preference', name: '接单偏好', labelWidth: '100px', type: 'input' },
        { keyword: 'supplier', name: '关联供应商', labelWidth: '100px', type: 'input' },
        { keyword: 'wxCode', name: '微信号', labelWidth: '100px', type: 'input' },
        { keyword: 'phone', name: '手机', labelWidth: '100px', type: 'input' },
        { keyword: 'updator', name: '更新人', labelWidth: '100px', type: 'input' },
        { keyword: 'invitee', name: '邀请人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        { keyword: 'tagName', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        {
          keyword: 'region', name: '地域', valueName: 'label', labelName: 'label', checkStrictly: true, separator: '-',
          childrenVal: 'children', type: 'cascaderSelect', options: allRegionData, emitPath: true, filterable: true
        },
        { keyword: 'status', name: '状态', type: 'select', options: this.status },
        { keyword: 'linkAccountStatus', name: '关联状态', type: 'select', options: this.linkAccountStatus },
        { keyword: 'settledInType', name: '入驻类型', type: 'select', options: [{ value: 0, label: '非签约接单入驻' }, { value: 1, label: '签约接单入驻' }] },
        // 日期
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'updateTime', name: '更新时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'lastLoginTime', name: '最近登录时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    moreOpeatorOptions() {
      return [
        {
          label: '更新账号信息',
          handelClick: this.updateAccount,
          auth: hasRouteAuth('crm:flyUser:updateAccount'),
          disabled: this.isAccountUpdating,
          loading: this.isAccountUpdating,
          type: 'iconTip',
          tip: '飞来用户填写的账号信息将更新至账号资源详情'
        },
        {
          label: '更新达人信息',
          handelClick: this.updateUser,
          auth: hasRouteAuth('crm:flyUser:updateSupplier'),
          disabled: this.isUserUpdating,
          loading: this.isUserUpdating,
          type: 'iconTip',
          tip: '将用户填写个人资料、收款账号更新至供应商信息'
        }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 200 : 0;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    },
    isAccountUpdating(newv, oldv) { // 监听是否更新完成
      this.clearTimer(newv, oldv);
    },
    isUserUpdating(newv, oldv) {
      this.clearTimer(newv, oldv);
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'flyUserDetail') {
      to.meta.isFromDetail = true;
    } else {
      to.meta.isFromDetail = false;
    }
    next();
  },
  created() {
    this.getUpdateStatus(true);// 组件被销毁,如果处在更新状态重启定时器（如用户刷新页面）
    this.platformList();
    this.queryTagTreeList();
  },
  activated() {
    if (this.$route.meta.isFromDetail) {
      this.fetchData();
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
      if (this.$route.query.accountName) {
        this.paramsObj = {};
        this.$set(this.paramsObj, 'accountName', this.$route.query.accountName);
        this.defaultSelectKey = 'accountName';
        this.fetchData(true);
      }
    }
  },
  methods: {
    hasRouteAuth,
    format,
    numberTextFormat,
    getFlyStatusColor,
    updateAccount() {
      // this.batchUpdate(0);
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择需要更新的用户');
        return;
      }
      const ids = this.multipleSelectionAll.map(el => el.id).join(',');
      this.$refs['updateCheckDialogRef'].openDialog(ids);
    },
    updateUser() {
      this.batchUpdate(1);
    },
    // 批量更新信息,type 0账号信息 1达人信息
    batchUpdate(type = 0) {
      if (!this.list.items.length) {
        this.$message.warning('暂无需更新的数据');
        return;
      }
      const title = `请确认是否更新${type === 0 ? '账号' : '达人'}信息`;
      showModal(title, '', {}).then(_ => {
        if (type === 0) {
          this.isAccountUpdating = true;
        } else {
          this.isUserUpdating = true;
        }
        // 开启轮询，获取更新情况
        if (!this.timer) {
          this.setTimer();
        }
        const data = {
          type,
          ids: this.multipleSelectionAll.length ? this.multipleSelectionAll.map(el => el.id).join(',') : null,
          ...this.formatParams()
        };
        batchUpdate(data).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
        }).catch(err => {
          console.log(err);
        });
      }).catch(_ => null);
    },
    // 每隔一段时间去查询是否在更新信息
    setTimer(time = 1500) {
      this.timer = setInterval(() => {
        this.getUpdateStatus();
      }, time);
    },
    getUpdateStatus(init = false) {
      getUpdateStatus().then(res => {
        this.isAccountUpdating = res.data.isAccountUpdating;
        this.isUserUpdating = res.data.isUserUpdating;
        if (init && (this.isAccountUpdating | this.isUserUpdating)) {
          this.setTimer();
        }
      }).catch(err => {
        console.log(err);
      });
    },
    // 刷新列表，清除定时器
    clearTimer(newv, oldv) {
      if (oldv && !newv) { // true=>false
        if (!this.isAccountUpdating && !this.isUserUpdating) { // 两者都完成清除定时器
          clearInterval(this.timer);
          this.timer = null;
          this.$message.success('更新信息成功');
          this.fetchData();
        }
      }
    },
    // 一键启用/禁用 1启用 2禁用
    batchSetStatus(status) {
      const ids = this.multipleSelectionAll.map(el => el.id).join(',');
      if (!ids) {
        this.$message.warning(`请选择要${status === 1 ? '启用' : '禁用'}的用户`);
        return;
      }
      const msg = `请确认是否要对勾选用户进行一键${status === 1 ? '启用' : '禁用'}？`;
      showModal(msg, '', {}).then(_ => {
        this.batchLoading = true;
        const data = {
          ids,
          status
        };
        batchSetStatus(data).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.fetchData();
            this.clearMixinSelection && this.clearMixinSelection();
            this.multipleSelectionAll = [];
          }
          this.batchLoading = false;
        }).catch(err => {
          this.batchLoading = false;
          console.log(err);
        });
      }).catch(err => {
        console.log(err);
      });
    },
    settledInTypeMap(type) {
      return {
        0: '非签单接单入驻',
        1: '签单接单入驻'
      }[type] || '--';
    },
    handleFans(fans) {
      if (!fans) { return ''; }
      if (fans.search('~') !== -1) {
        let arr = [];
        arr = fans.split('~');
        return `${this.numberTextFormat(arr[0], 1)}~${this.numberTextFormat(arr[1], 1)}`;
      }
      return this.numberTextFormat(fans, 1);
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 标签
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    getAffiliatedSuppliers(list) {
      if (Array.isArray(list) && list.length) {
        const allSupplierData = list.filter(item => item.supplierName) || [];
        const suppliers = allSupplierData.map(item => item.supplierName) || [];
        return suppliers.join();
      }
    },
    getTabs() {
      const params = this.formatParams();
      tabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = {
        page: this.page,
        perPage: this.perPage,
        tabStatus: this.tabStatus,
        ...this.formatParams()
      };
      flyUserList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
      }).catch(err => {
        this.list.isInit = false;
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      Object.keys(paramsObj).forEach(key => {
        if (paramsObj[key] && Array.isArray(paramsObj[key])) {
          paramsObj[key] = paramsObj[key].join(`${key === 'region' ? '-' : ','}`);
        }
      });
      paramsObj.sortName = this.sortName;
      paramsObj.sortType = this.sortType;
      // tab选中信息更新时传参
      paramsObj.waitUpdate = this.tabStatus == null ? 1 : null;
      return paramsObj;
    },
    toDetail(row) {
      this.$router.push({
        name: 'flyUserDetail',
        query: {
          flyUserId: row.id
        }
      });
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleUpdateCheckClose() {
      this.clearMixinSelection && this.clearMixinSelection();
      this.fetchData(true);
    },
    // 新增供应商
    toCreateSupplier() {
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.el-dropdown-link{
  display: block;
  position: relative;
  &.border-left {
    padding-left:6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
}
@keyframes new-tag-zoom {
  0% { transform: scale(1) }
  25% { transform: scale(1.1) }
  50% { transform: scale(1) }
  75% { transform: scale(0.9) }
  100% { transform: scale(1) }
}
.new-tag {
  height: 16px;
  line-height: 16px;
  border-radius: 999px 999px 999px 0;
  background-color: #ff3333;
  color: #fff;
  margin-left: 4px;
  padding: 0 4px;
  font-size: 12px;
  animation: new-tag-zoom 1s ease infinite;
}
.dropdown-btn{
  font-size: 14px !important;
  font-family: PingFangSC-Regular, PingFang SC;
}
	.flyUser{
		.flyUser-list{
			margin: 16px 16px 0 16px;
			background-color: #fff;
			padding: 20px 24px 55px 24px;
		}
    .status-0{
      color: #2DC500;
    };
    .status-2{
      color: #FF0000;
    };
		.menu-item{
			width: 90px;
			text-align: center;
		}
    .operate{
      display: flex;
      align-items: center;
    }
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
    .filter {
			display: flex;
			align-items: center;
			margin-bottom: 16px;
			.create-btn{
					height: 32px;
					font-size: 14px;
					padding: 0 15px;
			}
    }
    .pointer{
      cursor: pointer;
    }
	}
  .submit-btn {
    ::v-deep .el-button {
      padding: 7px 10px !important;
    }
  }
  .enable-btn {
    display: flex;
    align-items: center;
    .tipIcon {
      width: 16px;
      height: 16px;
      flex-shrink: 0;
      margin-left: 4px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
  }
  .supplier-tooltip-name {
    cursor: pointer;
    &:hover {
      color: #406EFF;
    }
  }
  .dropdown-img {
    width: 24px;
    height: 24px;
    flex-shrink: 0;
    img {
      width: 100%;
      height: 100%;
    }
  }
</style>
